package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.dto.UserDetailsDto;
import cn.itsource.ymcc.service.ILoginService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Security 查询数据库获取用户信息的类
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username",username);
        Login login = loginService.selectOne(wrapper);

        if(login==null){
            return null;
        }

        // 权限列表
        List<String> list = loginService.getAuthorByLoginID(login.getId());
        Collection<? extends GrantedAuthority> authorities = list.stream().map(s->new SimpleGrantedAuthority(s)).collect(Collectors.toList());

        UserDetailsDto detailsDto = new UserDetailsDto(login.getUsername(),login.getId(),authorities);

        UserDetails userDetails = new User(JSON.toJSONString(detailsDto),
                login.getPassword(),
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                authorities
                );

        return userDetails;
    }
}
